// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const giftCollection = db.collection('gift_list')
const MAX_LIMIT = 100 // 单次查询最大限制

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  
  // 获取请求参数
  const { id, status } = event
  
  if (!id) {
    return {
      success: false,
      message: '礼单ID不能为空'
    }
  }
  
  try {
    // 安全检查：确保用户只能更新自己的礼单
    const giftItem = await giftCollection.doc(id).get()
    
    if (!giftItem.data || giftItem.data.openid !== openid) {
      return {
        success: false,
        message: '无权限修改此礼单'
      }
    }
    
    // 更新回礼状态
    await giftCollection.doc(id).update({
      data: {
        is_return_gift: status,
        update_time: db.serverDate()
      }
    })
    
    console.log(`成功更新礼单状态: id=${id}, status=${status}`)
    
    // 获取更新后的统计数据（优化查询）
    let totalCount = 0
    let totalAmount = 0
    let returnedCount = 0
    
    // 1. 获取总数 - 直接使用count API
    const countResult = await giftCollection.where({ openid }).count()
    totalCount = countResult.total
    console.log(`总记录数: ${totalCount}`)
    
    // 2. 获取已回礼数 - 直接使用count API
    const returnedCountResult = await giftCollection.where({
      openid,
      is_return_gift: true
    }).count()
    returnedCount = returnedCountResult.total
    console.log(`已回礼记录数: ${returnedCount}`)
    
    // 3. 计算总金额 - 分批次获取所有数据
    const batchTimes = Math.ceil(totalCount / MAX_LIMIT)
    console.log(`需要分${batchTimes}批查询计算总金额`)
    
    for (let i = 0; i < batchTimes; i++) {
      const res = await giftCollection
        .where({ openid })
        .skip(i * MAX_LIMIT)
        .limit(MAX_LIMIT)
        .get()
      
      console.log(`第${i+1}批获取到${res.data.length}条记录`)
      
      res.data.forEach(item => {
        if (item.amount && !isNaN(Number(item.amount))) {
          totalAmount += Number(item.amount)
        }
      })
    }
    
    // 4. 计算未回礼数
    const notReturnedCount = totalCount - returnedCount
    
    // 5. 计算已回礼金额 - 分批次获取所有已回礼的数据
    let returnedAmount = 0
    const returnedBatchTimes = Math.ceil(returnedCount / MAX_LIMIT)
    
    for (let i = 0; i < returnedBatchTimes; i++) {
      const res = await giftCollection
        .where({ 
          openid,
          is_return_gift: true
        })
        .skip(i * MAX_LIMIT)
        .limit(MAX_LIMIT)
        .get()
      
      console.log(`第${i+1}批获取到${res.data.length}条已回礼记录`)
      
      res.data.forEach(item => {
        if (item.amount && !isNaN(Number(item.amount))) {
          returnedAmount += Number(item.amount)
        }
      })
    }
    
    // 6. 计算未回礼金额
    const notReturnedAmount = totalAmount - returnedAmount
    
    // 准备总体统计和筛选统计数据
    const totalStats = {
      totalCount,
      totalAmount: totalAmount.toFixed(2),
      returnedCount,
      notReturnedCount
    }
    
    // 筛选统计 - 根据当前礼单的回礼状态
    const filteredStats = {
      // 如果当前礼单已回礼，则筛选统计中展示已回礼的数据
      totalCount: status ? returnedCount : notReturnedCount,
      totalAmount: status ? returnedAmount.toFixed(2) : notReturnedAmount.toFixed(2),
      returnedCount: status ? returnedCount : 0,
      notReturnedCount: status ? 0 : notReturnedCount
    }
    
    console.log(`总体统计结果: 总数=${totalCount}, 总金额=${totalAmount.toFixed(2)}, 已回礼=${returnedCount}, 未回礼=${notReturnedCount}`)
    console.log(`筛选统计结果: 总数=${filteredStats.totalCount}, 总金额=${filteredStats.totalAmount}, 已回礼=${filteredStats.returnedCount}, 未回礼=${filteredStats.notReturnedCount}`)
    
    return {
      success: true,
      message: status ? '已设为已回礼' : '已设为未回礼',
      stats: totalStats,
      totalStats,
      filteredStats
    }
  } catch (err) {
    console.error('更新礼单状态失败', err)
    return {
      success: false,
      message: '更新失败',
      error: err
    }
  }
} 